<template>
  <view id="map" class="uni-map"></view>
</template>

<script lang="ts" setup>
  import type { ExpressData } from '@/types/order'
  import AMapLoader from '@amap/amap-jsapi-loader'
  import { onMounted } from 'vue'
  // 导入图标资源
  import carImg from '@/static/images/car.png'
  import startImg from '@/static/images/start.png'
  import endImg from '@/static/images/end.png'

  interface Props {
    logisticsInfo: ExpressData
  }
  const props = defineProps<Props>()

  onMounted(async () => {
    ;(window as any)._AMapSecurityConfig = {
      securityJsCode: 'd38de6955019842e89194996a461e8dc',
    }

    const AMap = await AMapLoader.load({
      key: 'fc6bc3717c09e3d439823d9814eca279', // 申请好的Web端开发者Key，首次调用 load 时必填
      version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: ['AMap.Scale'], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
    })
    let map = new AMap.Map('map', {
      // 设置地图容器id
      viewMode: '3D', // 是否为3D地图模式
      zoom: 11, // 初始化地图级别
      center: [116.397428, 39.90923], // 初始化地图中心点位置
    })

    AMap.plugin('AMap.Driving', function () {
      const driving = new AMap.Driving({
        map: map, //当指定此参数后，搜索结果的标注、线路等均会自动添加到此地图上
        showTraffic: false,
        hideMarkers: true, //是否隐藏默认标记点
      })
      const start = props.logisticsInfo.logisticsInfo.pop()
      const end = props.logisticsInfo.logisticsInfo.shift()

      //标记位置
      const StarMarker = new AMap.Marker({
        position: [start?.longitude, start?.latitude],
        icon: startImg,
        anchor: 'bottom-center',
      })
      map.add(StarMarker)

      const EndMarker = new AMap.Marker({
        position: [end?.longitude, end?.latitude],
        icon: endImg,
        anchor: 'bottom-center',
      })
      map.add(EndMarker)

      const CarMarker = new AMap.Marker({
        position: [
          props.logisticsInfo.currentLocationInfo?.longitude,
          props.logisticsInfo.currentLocationInfo?.latitude,
        ],
        icon: carImg,
        anchor: 'bottom-center',
      })
      map.add(CarMarker)

      driving.search(
        [start?.longitude, start?.latitude],
        [end?.longitude, end?.latitude],
        {
          waypoints: props.logisticsInfo.logisticsInfo
            .map((item) => {
              return [item.longitude, item.latitude]
            })
            .reverse(),
        },
        function (status: any, result: any) {
          if (status === 'complete') {
            setTimeout(() => {
              map.setFitView([CarMarker])
              map.setZoom(10)
            }, 3000)
            console.log(result)
          } else {
            console.log('error')
          }
        }
      )
    })
  })
</script>

<style scoped></style>
